package com.lbank.spiderflow.core.utils;

import com.lbank.spiderflow.core.driver.DriverProvider;
import com.lbank.spiderflow.core.executor.shape.SeleniumExecutor;
import com.lbank.spiderflow.core.io.SeleniumResponse;
import com.lbank.spiderflow.model.SpiderNode;
import org.openqa.selenium.WebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Duration;
import java.util.Objects;


public class SeleniumHelper {
    private static final Logger logger = LoggerFactory.getLogger(SeleniumHelper.class);

    /**
     * 通过 selenium 模拟发送请求
     *
     * @param url
     * @return
     */
    public static String open(String url) {
        return open(url, null, null);
    }

    /**
     * 通过 selenium 模拟发送请求
     *
     * @param url
     * @param driverType
     * @return
     */
    public static String open(String url, String driverType) {
        return open(url, driverType, null);
    }

    /**
     * 通过 selenium 模拟发送请求
     *
     * @param url
     * @param driverType
     * @param loadPageWaitTime
     * @return
     */
    public static String open(String url, String driverType, Integer loadPageWaitTime) {
        WebDriver driver = null;
        try {
            SeleniumExecutor seleniumExecutor = SpringContextUtils.getBean(SeleniumExecutor.class);
            DriverProvider driverProvider = seleniumExecutor.getDriverProvider(driverType);
            driver = driverProvider.getWebDriver(new SpiderNode(), null);
            driver.get(url);
            //driver.switchTo().newWindow(WindowType.TAB);
            if (Objects.nonNull(loadPageWaitTime)) {
                driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(loadPageWaitTime));
            }
            SeleniumResponse response = new SeleniumResponse(driver);
            LogHelper.info("url={}", response.getUrl());
            return response.getHtml();
        } catch (Exception e) {
            logger.error("open url ={} failed. driverType={}", url, driverType, e);
        } finally {
            if (driver != null) {
                driver.quit();
            }
        }
        return "";
    }
}
